package top.maof.book.spider.develop.contents.two952;

import lombok.Data;
import top.maof.book.model.Book;
import top.maof.book.model.Contents;
import top.maof.book.spider.develop.Split;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.model.AfterExtractor;
import us.codecraft.webmagic.model.annotation.ExtractBy;
import us.codecraft.webmagic.model.annotation.HelpUrl;
import us.codecraft.webmagic.model.annotation.TargetUrl;

import java.util.Date;

/**
 * 二九小说网
 */
@Data
@TargetUrl("https://www.2952.cc/b/\\d+/\\d+/")
@HelpUrl({"https://www.2952.cc/top.html", "https://www.2952.cc/sort/\\d+_\\d+.html",
        "https://www.2952.cc/sort/\\d+.html", "https://www.2952.cc/quanben/sort/\\d+.html"})
public class Erjiu implements AfterExtractor, Split {

    @ExtractBy(value = "//div[@class=bookinfo]/div[@class=booktitle]/h1/a/text()")
    private String name;

    @ExtractBy(value = "//div[@class=bookinfo]/div[@class=booktitle]/h2/a/text()")
    private String author;

    @ExtractBy(value = "//div[@class=book]/a[@class=cover]/img/@src")
    private String img;
    // https://www.2952.cc/files/article/image/10/10344/10344s.jpg

    @ExtractBy(value = "//div[@class=container]/ol/li[2]/a/text()")
    private String classify;//科幻小说

    private Date updateDate;

    private Date insertDate = new Date();

    @ExtractBy(value = "//div[@class=bookinfo]/div[@class=bookintro]/p[1]/text()")
    private String synopsis;

    private String state;

    private String url;

    private String content;

    private Integer webId = 8;

    public static final String CHARSET = "utf-8";

    @Override
    public void afterProcess(Page page) {

        this.author = this.author.trim();
        this.name = this.name.trim();

        //img字段做处理
        if (!this.img.startsWith("http")) {
            if (this.img.startsWith("/"))
                //绝对地址
                this.img = "https://www.2952.cc" + this.img;
            else {
                //相对地址
                this.img = page.getUrl().toString().substring(0, page.getUrl().toString().lastIndexOf("/") + 1) + this.img;
            }
        }
        //获取该页面url
        this.setUrl(page.getRequest().getUrl());
    }

    @Override
    public Book getBook() {
        Book book = new Book();
        book.setName(this.name.trim());
        book.setAuthor(this.author.trim());
//        book.setState(this.state);
//        book.setImg(this.img);
//        book.setInsertDate(this.insertDate);
//        book.setClassify(this.classify);
//        book.setSynopsis(this.synopsis);
//        book.setUpdateDate(this.updateDate);
        return book;
    }

    @Override
    public Contents getContents() {
        Contents contents = new Contents();
        contents.setUrl(this.url);
        contents.setContent(this.content);
        contents.setWebId(this.webId);
        contents.setUpdateDate(this.updateDate);
        return contents;
    }

}
